//
//  UserIDSettingViewController.m
//  SIPphone
//
//  Created by wrt on 13-11-12.
//  Copyright (c) 2013年 wrtsoft. All rights reserved.
//

#import "UserIDSettingViewController.h"
#import "AppDelegate.h"
#import "ContactsDateBase.h"
#import "PromptChatDateBase.h"
#import "PostMessageDataBase.h"
#import "FriendRespondDateBase.h"
#import "HistoryDataBase.h"

@interface UserIDSettingViewController ()

@end

@implementation UserIDSettingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = NSLocalizedString(@"account settings", @"帐号配置 Account settings");
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //获取存在程序内的用户名和密码/ip/端口
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *tempUserName = [[NSString alloc] init];
    tempUserName = [defaults valueForKey:@"SAVEUSERNAME"];
    NSString *tempPassWord = [[NSString alloc] init];
    tempPassWord = [defaults valueForKey:@"SAVEPASSWORD"];
    NSString *tempDisplayName = [[NSString alloc] init];
    tempDisplayName = [defaults valueForKey:@"SAVEDISPLAYNAME"];
    NSString *tempIp = [[NSString alloc] init];
    tempIp = [defaults valueForKey:@"SAVEIPADDRESS"];
    NSString *tempPort = [[NSString alloc] init];
    tempPort = [defaults valueForKey:@"SAVEPORT"];

    
    if (tempUserName.length > 0 && tempPassWord.length > 0 && tempIp.length > 0 && tempPort.length > 0)
    {
        self.userNameTextfield.text = tempUserName;
        self.passwordTextfield.text = tempPassWord;
        self.nickTextfield.text = tempDisplayName;
        self.ipTextField.text = tempIp;
        self.portTextfield.text = tempPort;
    }
    
    
    self.isAutoRegister = [defaults boolForKey:@"ISAUTOREGISTERSTATUS"];
    if (self.isAutoRegister == YES)
    {
        [self.autoRegisterButton setBackgroundImage:[UIImage imageNamed:@"选中.png"] forState:UIControlStateNormal];
    }
    
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    interface.delegate = self;
    
    
}

- (IBAction)loginButtonPressed:(id)sender
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL isReachability = [defaults boolForKey:@"ISREACHABILITY"];
    if (self.userNameTextfield.text.length > 0 && self.passwordTextfield.text.length > 0 && self.ipTextField.text.length > 0 && self.portTextfield.text.length > 0 && self.nickTextfield.text.length > 0 && isReachability)
    {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        app.isFristOpen = 1;
//        SIPInterface *interface = [SIPInterface shareSIPInterface];
//        [interface closeRegisterUsers];
        //弹出警告窗口
        self.alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"loading", @"登录中 Loading") message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        [self.alertView show];
        //在里面加入旋转
        UIActivityIndicatorView *activeView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        //开始转
        [activeView startAnimating];
        activeView.center = CGPointMake(self.alertView.bounds.size.width/2,self.alertView.bounds.size.height-40.0f);
        [self.alertView addSubview:activeView];
        
        dispatch_async(dispatch_get_main_queue(),^{
            [self performSelector:@selector(agianRegisterUser) withObject:self afterDelay:2];
        });
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"please connect to the network and the content of the completed", @"请连接网络并将内容填写完整 Please connect to the network and the content of the completed") delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"好的 OK") otherButtonTitles: nil];
        [alert show];
    }
}

- (void)agianRegisterUser
{
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    [interface register:self.userNameTextfield.text passWord:self.passwordTextfield.text];
    [interface displayName:self.nickTextfield.text andUserName:self.userNameTextfield.text];
    [interface setServiceAddress:self.ipTextField.text andPort:[self.portTextfield.text intValue]];
//    [interface startRegisterUsers];
}

- (IBAction)autoLoginButtonPressed:(id)sender
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    //根据是否选中去改变按钮的图样，和将yes或者no存起来以便程序下次启动时不用再次手动登陆
    if (!self.isAutoRegister)
    {
        [defaults setBool:YES forKey:@"ISAUTOREGISTERSTATUS"];
        [self.autoRegisterButton setBackgroundImage:[UIImage imageNamed:@"选中.png"] forState:UIControlStateNormal];
    }
    else if(self.isAutoRegister)
    {
        [defaults setBool:NO forKey:@"ISAUTOREGISTERSTATUS"];
        [self.autoRegisterButton setBackgroundImage:[UIImage imageNamed:@"选择.png"] forState:UIControlStateNormal];
    }
    [defaults synchronize];
    self.isAutoRegister = !self.isAutoRegister;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -
#pragma mark textFieldResponder
//点击背景会取消输入框的输入
- (IBAction)backgroundPressed:(id)sender
{
    [self.userNameTextfield resignFirstResponder];
    [self.passwordTextfield resignFirstResponder];
    [self.nickTextfield resignFirstResponder];
    [self.portTextfield resignFirstResponder];
    [self.ipTextField resignFirstResponder];
}
//用户名输入点完成时取消键盘
- (IBAction)userNameEndOnExit:(id)sender
{
    [self.userNameTextfield resignFirstResponder];
}
//密码输入点完成时取消键盘
- (IBAction)passWordEndOnExit:(id)sender
{
    [self.passwordTextfield resignFirstResponder];
}
//昵称点完成时取消键盘
- (IBAction)nickEndOnExit:(id)sender
{
    [self.nickTextfield resignFirstResponder];
}
//服务器点完成时取消键盘
- (IBAction)ipEndOnExit:(id)sender
{
    [self.ipTextField resignFirstResponder];
}
//端口点击完成时取消键盘
- (IBAction)portEndOnExit:(id)sender
{
    [self.portTextfield resignFirstResponder];
}

#pragma mark -
#pragma mark SIPListenMethod
- (void)registerSuccessful //当注册成功时
{
    
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (app.isFristOpen == 1)
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        //个人状态 设置在线
        SIPInterface *interface = [SIPInterface shareSIPInterface];
        [interface setMyStatusWithInt:1];
        [defaults setInteger:1 forKey:@"SAVEMYSTATUS"];
        app.isFristOpen++;
        
        //创建用于存储联系人的数据库
        ContactsDateBase *contactsDb = [ContactsDateBase shareContactsDataBase];
        [contactsDb changeTableName:self.userNameTextfield.text];
        [contactsDb creatDB];
        [contactsDb readDB];
        
        //创建用于存储好友信息的数据库
        FriendRespondDateBase *friendRespondDB = [FriendRespondDateBase shareFriendRespondDateBase];
        [friendRespondDB changeTableName:self.userNameTextfield.text];
        [friendRespondDB creatDB];
        [friendRespondDB readDB];
        
        //创建用于即时聊天的数据库
        PromptChatDateBase *promptDB = [PromptChatDateBase sharePromptChatDB];
        [promptDB changeTableName:self.userNameTextfield.text];
        [promptDB creatDB];
        [promptDB readDB];
        
        //创建用于历史记录的数据库
        HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
        [historyDB changeTableName:self.userNameTextfield.text];
        [historyDB createDb];
        [historyDB loadArray:0];
        
        //创建用于推送消息的数据库
        PostMessageDataBase *postMsgDB = [PostMessageDataBase sharePostMessageDateBase];
        [postMsgDB changeTableName:self.userNameTextfield.text];
        [postMsgDB createDb];
        [postMsgDB loadArray];
        
        
//        NSMutableArray *tempUserNameArray = [[NSMutableArray alloc] init];
//        NSMutableArray *tempIpArray = [[NSMutableArray alloc] init];
        
        //将列表中的好友传到底层去
//        for (int i = 0; i < contactsDb.isFriendArray.count; i++)
//        {
//            if ([contactsDb.isFriendArray[i] isEqualToString:@"好友"])
//            {
//                [tempUserNameArray addObject:contactsDb.userNameArray[i]];
//                [tempIpArray addObject:contactsDb.ipPortArray[i]];
//            }
//        }
//        
//        for (int j = 0; j < tempUserNameArray.count; j++)
//        {
//            SIPInterface *interface = [SIPInterface shareSIPInterface];
//            [interface addFriendsWithUserName:tempUserNameArray[j] andDisPlayName:@"" andIp:tempIpArray[j]];
//        }
    }
    
    dispatch_async(dispatch_get_main_queue(),^{       //在主线程中操作
        [self.alertView dismissWithClickedButtonIndex:0 animated:YES];
        NSString *userName = [[NSString alloc] init];
        userName = self.userNameTextfield.text;
        NSString *passWord = [[NSString alloc] init];
        passWord = self.passwordTextfield.text;
        NSString *displayName = [[NSString alloc] init];
        displayName = self.nickTextfield.text;
        NSString *ipAddress = [[NSString alloc] init];
        ipAddress = self.ipTextField.text;
        NSString *port = [[NSString alloc] init];
        port = self.portTextfield.text;
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:userName forKey:@"SAVEUSERNAME"];
        [defaults setObject:passWord forKey:@"SAVEPASSWORD"];
        [defaults setObject:displayName forKey:@"SAVEDISPLAYNAME"];
        [defaults setObject:ipAddress forKey:@"SAVEIPADDRESS"];
        [defaults setObject:port forKey:@"SAVEPORT"];
        //成功注册后将用户名和密码存起来
        [defaults setBool:YES forKey:@"REGISTERSTATUS"];
        [defaults synchronize];
        [self.navigationController popViewControllerAnimated:YES]; //返回上层界面
    });
}

- (void)registerFailed  //当注册失败时 弹出提醒框
{
    dispatch_async(dispatch_get_main_queue(),^{
        [self.alertView dismissWithClickedButtonIndex:0 animated:YES];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"registration fails, check to see if you enter an incorrect username and password, or a network connection error", @"注册失败，请检查是否输入了错误的用户名和密码，或者网络连接错误 Registration fails, check to see if you enter an incorrect username and password, or a network connection error") delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"好的 OK") otherButtonTitles: nil];
        [alert show];
    });
}


@end
